package net.lab1024.sa.admin.module.business.pdf.util;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.Tesseract;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * OCR测试工具
 *
 * @Author 1024创新实验室
 */
@Slf4j
@Component
public class OcrTestTool {

    /**
     * 测试Tesseract基本功能
     */
    public Map<String, Object> testTesseractBasic(String tessdataPath) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Tesseract tesseract = new Tesseract();
            tesseract.setDatapath(tessdataPath);
            
            // 测试语言包
            String[] languages = {"chi_sim", "eng", "chi_sim+eng"};
            Map<String, Boolean> languageTests = new HashMap<>();
            
            for (String lang : languages) {
                try {
                    tesseract.setLanguage(lang);
                    // 创建一个简单的测试图像（白色背景）
                    BufferedImage testImage = createTestImage();
                    String ocrResult = tesseract.doOCR(testImage).trim();
                    languageTests.put(lang, !ocrResult.isEmpty());
                    log.info("语言包 {} 测试结果: {}", lang, ocrResult);
                } catch (Exception e) {
                    languageTests.put(lang, false);
                    log.error("语言包 {} 测试失败: {}", lang, e.getMessage());
                }
            }
            
            result.put("success", true);
            result.put("languageTests", languageTests);
            result.put("message", "Tesseract基本功能测试完成");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", e.getMessage());
            log.error("Tesseract基本功能测试失败: {}", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 测试中文识别能力
     */
    public Map<String, Object> testChineseRecognition(String tessdataPath, File testImageFile) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Tesseract tesseract = new Tesseract();
            tesseract.setDatapath(tessdataPath);
            tesseract.setLanguage("chi_sim");
            
            // 中文识别优化参数
            tesseract.setTessVariable("preserve_interword_spaces", "1");
            tesseract.setTessVariable("tessedit_pageseg_mode", "3");
            tesseract.setTessVariable("tessedit_ocr_engine_mode", "3");
            tesseract.setTessVariable("textord_heavy_nr", "0");
            tesseract.setTessVariable("textord_min_linesize", "0.5");
            
            BufferedImage image = ImageIO.read(testImageFile);
            if (image == null) {
                result.put("success", false);
                result.put("error", "无法读取测试图像");
                return result;
            }
            
            String ocrResult = tesseract.doOCR(image).trim();
            
            result.put("success", true);
            result.put("ocrResult", ocrResult);
            result.put("resultLength", ocrResult.length());
            result.put("hasChinese", containsChinese(ocrResult));
            result.put("chineseCharCount", countChineseChars(ocrResult));
            
            log.info("中文识别测试结果: {}", ocrResult);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", e.getMessage());
            log.error("中文识别测试失败: {}", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 创建测试图像
     */
    private BufferedImage createTestImage() {
        BufferedImage image = new BufferedImage(100, 50, BufferedImage.TYPE_INT_RGB);
        for (int y = 0; y < 50; y++) {
            for (int x = 0; x < 100; x++) {
                image.setRGB(x, y, 0xFFFFFF); // 白色背景
            }
        }
        return image;
    }
    
    /**
     * 检查是否包含中文字符
     */
    private boolean containsChinese(String text) {
        if (text == null) return false;
        for (char c : text.toCharArray()) {
            if (c >= 0x4E00 && c <= 0x9FFF) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 统计中文字符数量
     */
    private int countChineseChars(String text) {
        if (text == null) return 0;
        int count = 0;
        for (char c : text.toCharArray()) {
            if (c >= 0x4E00 && c <= 0x9FFF) {
                count++;
            }
        }
        return count;
    }
    
    /**
     * 检查语言包文件
     */
    public Map<String, Object> checkLanguagePacks(String tessdataPath) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            File tessdataDir = new File(tessdataPath);
            if (!tessdataDir.exists() || !tessdataDir.isDirectory()) {
                result.put("success", false);
                result.put("error", "tessdata目录不存在: " + tessdataPath);
                return result;
            }
            
            String[] requiredLanguages = {"chi_sim", "eng"};
            Map<String, Boolean> languagePackStatus = new HashMap<>();
            
            for (String lang : requiredLanguages) {
                File langFile = new File(tessdataDir, lang + ".traineddata");
                boolean exists = langFile.exists();
                languagePackStatus.put(lang, exists);
                
                if (exists) {
                    long fileSize = langFile.length();
                    log.info("语言包 {} 存在，大小: {} bytes", lang, fileSize);
                } else {
                    log.warn("语言包 {} 不存在", lang);
                }
            }
            
            result.put("success", true);
            result.put("tessdataPath", tessdataPath);
            result.put("languagePackStatus", languagePackStatus);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", e.getMessage());
            log.error("检查语言包失败: {}", e.getMessage());
        }
        
        return result;
    }
} 